<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI WebSocket 多轮对话测试</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .chat-container {
            height: 500px;
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow-y: auto;
            padding: 15px;
            margin-bottom: 20px;
            background-color: #fafafa;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 8px;
            max-width: 80%;
        }
        .user-message {
            background-color: #007bff;
            color: white;
            margin-left: auto;
            text-align: right;
        }
        .ai-message {
            background-color: #e9ecef;
            color: #333;
        }
        .system-message {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
            font-style: italic;
        }
        .tool-call {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .tool-result {
            background-color: #cce5ff;
            color: #004085;
            border: 1px solid #b3d9ff;
        }
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .input-container {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        .input-container input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        .input-container button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }
        .input-container button:hover {
            background-color: #0056b3;
        }
        .input-container button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .controls {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        .controls button {
            padding: 8px 16px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: white;
            cursor: pointer;
        }
        .controls button:hover {
            background-color: #f8f9fa;
        }
        .status {
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
            font-weight: bold;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
        .session-info {
            background-color: #e2e3e5;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
            font-size: 12px;
        }
        .task-info {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
            font-size: 12px;
        }
        .task-status {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: bold;
        }
        .task-status.processing {
            background-color: #007bff;
            color: white;
        }
        .task-status.completed {
            background-color: #28a745;
            color: white;
        }
        .task-status.failed {
            background-color: #dc3545;
            color: white;
        }
        .timestamp {
            font-size: 11px;
            color: #6c757d;
            margin-top: 5px;
        }
        .turn-info {
            font-size: 11px;
            color: #007bff;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>AI WebSocket 多轮对话测试</h1>
        
        <div id="status" class="status disconnected">未连接</div>
        
        <div class="controls">
            <button onclick="connect()">连接</button>
            <button onclick="disconnect()">断开连接</button>
            <button onclick="createSession()">创建会话</button>
            <button onclick="clearSession()">清空会话</button>
        </div>
        
        <div id="sessionInfo" class="session-info" style="display: none;"></div>
        
        <div id="taskInfo" class="task-info" style="display: none;"></div>
        
        <div id="chatContainer" class="chat-container"></div>
        
        <div class="input-container">
            <input type="text" id="messageInput" placeholder="输入消息..." onkeypress="handleKeyPress(event)">
            <button onclick="sendMessage()" id="sendButton" disabled>发送</button>
        </div>
        
        <div>
            <h3>测试用例：</h3>
            <button onclick="testGitlabProjects()">测试：查询GitLab项目</button>
            <button onclick="testJenkinsBuilds()">测试：查询Jenkins构建</button>
            <button onclick="testSystemStatus()">测试：检查系统状态</button>
            <button onclick="testComplexWorkflow()">测试：复杂工作流</button>
        </div>
    </div>

    <script>
        let ws = null;
        let sessionId = null;
        let isConnected = false;
        let currentTask = null;

        function connect() {
            if (ws) {
                ws.close();
            }

            // 注意：这里需要替换为实际的WebSocket地址和token
            const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NTQwNDI5MDQsImlkIjoxLCJuYW1lIjoiYWRtaW4ifQ.pEin2lgPyQ2zDaEefzJOkwAubowf0ppzL-090ILbGYs'; // 需要替换为实际的JWT token
            const wsUrl = `ws://localhost:8080/ai/ws?token=${token}`;
            
            ws = new WebSocket(wsUrl, ['ai-chat']);
            
            ws.onopen = function(event) {
                isConnected = true;
                updateStatus('已连接', 'connected');
                document.getElementById('sendButton').disabled = false;
                addMessage('system', '已连接到AI WebSocket服务器');
            };
            
            ws.onmessage = function(event) {
                const message = JSON.parse(event.data);
                handleWebSocketMessage(message);
            };
            
            ws.onclose = function(event) {
                isConnected = false;
                updateStatus('连接已断开', 'disconnected');
                document.getElementById('sendButton').disabled = true;
                addMessage('system', '连接已断开');
            };
            
            ws.onerror = function(error) {
                console.error('WebSocket错误:', error);
                addMessage('error', '连接错误: ' + error.message);
            };
        }

        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }

        function createSession() {
            if (!isConnected) {
                alert('请先连接WebSocket');
                return;
            }
            
            const message = {
                type: 'create_session',
                id: generateId(),
                content: '',
                data: {
                    userId: 'test-user'
                },
                timestamp: Date.now()
            };
            
            ws.send(JSON.stringify(message));
        }

        function clearSession() {
            if (!isConnected || !sessionId) {
                alert('请先创建会话');
                return;
            }
            
            const message = {
                type: 'clear_session',
                id: generateId(),
                sessionId: sessionId,
                content: '',
                data: {},
                timestamp: Date.now()
            };
            
            ws.send(JSON.stringify(message));
        }

        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message || !isConnected || !sessionId) {
                if (!sessionId) alert('请先创建会话');
                return;
            }
            
            // 检查是否有正在进行的任务
            if (currentTask && currentTask.status === 'processing') {
                alert('有任务正在处理中，请等待完成后再发送新消息');
                return;
            }
            
            const wsMessage = {
                type: 'user_message',
                id: generateId(),
                sessionId: sessionId,
                content: message,
                data: {},
                timestamp: Date.now()
            };
            
            ws.send(JSON.stringify(wsMessage));
            addMessage('user', message);
            input.value = '';
            
            // 设置临时任务状态，等待后端确认
            currentTask = { id: 'pending', status: 'processing' };
        }

        function handleWebSocketMessage(message) {
            console.log('收到消息:', message);
            
            switch (message.type) {
                case 'session_info':
                    updateSessionInfo(message.data);
                    addMessage('system', message.content);
                    break;
                case 'session_created':
                    sessionId = message.sessionId;
                    updateSessionInfo(message.data.session);
                    addMessage('system', `会话创建成功: ${sessionId}`);
                    if (message.data.features) {
                        const features = Object.entries(message.data.features)
                            .filter(([key, value]) => value)
                            .map(([key]) => key)
                            .join(', ');
                        addMessage('system', `支持功能: ${features}`);
                    }
                    break;
                case 'session_loaded':
                    sessionId = message.sessionId;
                    updateSessionInfo(message.data.session);
                    addMessage('system', `会话加载成功: ${sessionId}`);
                    break;
                case 'session_cleared':
                    addMessage('system', '会话已清空');
                    clearTaskInfo();
                    break;
                case 'ai_response':
                    const turnInfo = message.data.turn ? `[第${message.data.turn}轮]` : '';
                    const taskId = message.data.taskId ? ` 任务:${message.data.taskId.slice(-8)}` : '';
                    addMessage('ai', message.content, turnInfo + taskId);
                    break;
                case 'tool_call':
                    const toolInfo = `工具: ${message.data.toolName}, 参数: ${JSON.stringify(message.data.parameters)}`;
                    const taskInfo1 = message.data.taskId ? ` 任务:${message.data.taskId.slice(-8)}` : '';
                    addMessage('tool-call', `${message.content}\n${toolInfo}`, `[第${message.data.turn}轮]${taskInfo1}`);
                    updateTaskInfo(message.data.taskId, 'processing', `正在执行: ${message.data.toolName}`);
                    break;
                case 'tool_result':
                    const resultStatus = message.data.success ? '✅ 成功' : '❌ 失败';
                    const taskInfo2 = message.data.taskId ? ` 任务:${message.data.taskId.slice(-8)}` : '';
                    addMessage('tool-result', `${resultStatus}\n${message.content}`, `[第${message.data.turn}轮]${taskInfo2}`);
                    break;
                case 'task_completed':
                    if (message.data && message.data.taskId) {
                        updateTaskInfo(message.data.taskId, 'completed', '任务处理完成');
                        addMessage('system', `任务 ${message.data.taskId.slice(-8)} 已完成`);
                    }
                    break;
                case 'task_failed':
                    if (message.data && message.data.taskId) {
                        updateTaskInfo(message.data.taskId, 'failed', '任务处理失败');
                        addMessage('system', `任务 ${message.data.taskId.slice(-8)} 执行失败`);
                    }
                    break;
                case 'task_status_update':
                    if (message.data && message.data.canSendNewMessage) {
                        // 任务结束，允许发送新消息
                        currentTask = null;
                        addMessage('system', '可以发送新消息了');
                    }
                    break;
                case 'error':
                    addMessage('error', message.content);
                    if (currentTask) {
                        updateTaskInfo(currentTask.id, 'failed', '任务执行失败');
                    }
                    break;
            }
        }

        function addMessage(type, content, extra = '') {
            const container = document.getElementById('chatContainer');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}-message`;
            
            const timestamp = new Date().toLocaleTimeString();
            messageDiv.innerHTML = `
                ${extra ? `<div class="turn-info">${extra}</div>` : ''}
                <div>${content}</div>
                <div class="timestamp">${timestamp}</div>
            `;
            
            container.appendChild(messageDiv);
            container.scrollTop = container.scrollHeight;
        }

        function updateStatus(text, className) {
            const status = document.getElementById('status');
            status.textContent = text;
            status.className = `status ${className}`;
        }

        function updateSessionInfo(data) {
            const info = document.getElementById('sessionInfo');
            if (data) {
                info.style.display = 'block';
                info.innerHTML = `
                    <strong>会话信息:</strong><br>
                    ID: ${data.id || sessionId}<br>
                    可用工具: ${data.availableTools ? data.availableTools.length : 0} 个<br>
                    任务历史: ${data.taskHistory ? data.taskHistory.length : 0} 个<br>
                    当前任务: ${data.currentTask ? '进行中' : '无'}<br>
                    创建时间: ${data.createdAt ? new Date(data.createdAt).toLocaleString() : '未知'}
                `;
            }
        }

        function updateTaskInfo(taskId, status, description) {
            if (!taskId) return;
            
            // 更新当前任务状态
            if (status === 'processing') {
                currentTask = { id: taskId, status: status };
            } else if (status === 'completed' || status === 'failed') {
                // 任务结束，清理当前任务状态，允许发送新消息
                currentTask = null;
            }
            
            const info = document.getElementById('taskInfo');
            info.style.display = 'block';
            
            const statusClass = status === 'processing' ? 'processing' : 
                               status === 'completed' ? 'completed' : 
                               status === 'failed' ? 'failed' : '';
            
            const taskTitle = (status === 'completed' || status === 'failed') ? '最近任务:' : '当前任务:';
            
            info.innerHTML = `
                <strong>${taskTitle}</strong><br>
                ID: ${taskId.slice(-8)}<br>
                状态: <span class="task-status ${statusClass}">${getStatusText(status)}</span><br>
                描述: ${description}<br>
                时间: ${new Date().toLocaleTimeString()}
            `;
            
            if (status === 'completed' || status === 'failed') {
                setTimeout(() => {
                    info.style.display = 'none';
                }, 5000); // 5秒后隐藏已完成的任务信息
            }
        }

        function clearTaskInfo() {
            currentTask = null;
            const info = document.getElementById('taskInfo');
            info.style.display = 'none';
        }

        function getStatusText(status) {
            switch (status) {
                case 'processing': return '处理中';
                case 'completed': return '已完成';
                case 'failed': return '失败';
                case 'pending': return '等待中';
                default: return status;
            }
        }

        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }

        function generateId() {
            return 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        // 测试用例
        function testGitlabProjects() {
            document.getElementById('messageInput').value = '请帮我查询GitLab项目列表，限制10个项目';
            sendMessage();
        }

        function testJenkinsBuilds() {
            document.getElementById('messageInput').value = '查询最近的Jenkins构建记录，我想了解构建状态';
            sendMessage();
        }

        function testSystemStatus() {
            document.getElementById('messageInput').value = '检查系统状态，包括数据库和Jenkins连接情况';
            sendMessage();
        }

        function testComplexWorkflow() {
            document.getElementById('messageInput').value = '我想部署一个项目，请先查询可用的GitLab项目，然后检查相关的Jenkins构建状态，最后告诉我系统是否准备好进行部署';
            sendMessage();
        }

        // 页面加载时自动连接（可选）
        // window.onload = function() {
        //     connect();
        // };
    </script>
</body>
</html>